package com.biter;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.waps.AppConnect;

import com.biter.bean.MarketItemBean;
import com.biter.bean.MarketTickerBean;
import com.biter.config.ConfigDef;
import com.biter.util.Formater;
import com.biter.util.Util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class QuotationActivity extends Activity {

	private String TAG = "QuotationActivity";
	private List<Map<String, Object>> depthDataList = null;
	private List<Map<String, Object>> tradeDataList = null;
	private ListView depthListView = null;
	private ListView tradeListView = null;
	private Context context = null;
	private Handler myHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				SimpleAdapter depthsimpleAdapter = (SimpleAdapter)depthListView.getAdapter();
				depthsimpleAdapter.notifyDataSetChanged();
				TradeAdapter tradesimpleAdapter = (TradeAdapter)tradeListView.getAdapter();
				tradesimpleAdapter.notifyDataSetChanged();
				
				String ticker_data = String.valueOf(msg.obj);
				MarketItemBean mb = new MarketItemBean(getWindow().getDecorView());
				mb.setJsonData(ticker_data, "");

				break;
			default:
				break;
			}
		}
		
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quotation);
		context = this;
		if(Util.checkShowAd(context)&&AppConnect.getInstance(this).hasPopAd(this))
		   AppConnect.getInstance(this).showPopAd(this);
		
		depthDataList = new ArrayList<Map<String,Object>>();	
		depthListView = (ListView) findViewById(R.id.dealList);
		SimpleAdapter depthadapter = new SimpleAdapter(this, depthDataList,
				R.layout.list_item_depth,
				new String[] { "buycount", "buyprice", "sellprice", "sellcount" }, new int[] {
						R.id.tvBuyCount, R.id.tvBuyPrice, R.id.tvSellPrice,
						R.id.tvSellCount });
		depthListView.setAdapter(depthadapter);
		
		tradeDataList = new ArrayList<Map<String,Object>>();
		tradeListView = (ListView) findViewById(R.id.tradeList);
		TradeAdapter tradeadapter = new TradeAdapter(this,tradeDataList);
		tradeListView.setAdapter(tradeadapter);
		
		(new Thread(new getDepthData())).start();
		
	}

	
	class getDepthData implements Runnable{

		public void run() {

			try {
				
				if(depthDataList==null){
					depthDataList = new ArrayList<Map<String,Object>>();
						
					tradeDataList = new ArrayList<Map<String,Object>>();

				}else {
					depthDataList.clear();
					tradeDataList.clear();
				}
				
				Map<String, Object> depthheadermap = new HashMap<String, Object>();
				depthheadermap.put("buycount", "委单量");
				depthheadermap.put("buyprice", "买入价");
				depthheadermap.put("sellprice", "卖出价");
				depthheadermap.put("sellcount", "委单量");
				depthDataList.add(depthheadermap);
				
				Map<String, Object> tradeheadermap = new HashMap<String, Object>();
				tradeheadermap.put("date", "成交时间");
				tradeheadermap.put("price", "成交价格");
				tradeheadermap.put("amount", "成交数量");
				tradeheadermap.put("type", "buy");
				tradeDataList.add(tradeheadermap);
				
				String return_depth_data = Util.getHtml(ConfigDef.CHINA_BITER_DEPTH, "utf-8");
				JSONObject dataObject = JSONObject.fromObject(return_depth_data);
				JSONArray askArray = dataObject.getJSONArray("asks");
				JSONArray bidsArray = dataObject.getJSONArray("bids");
				for(int i = 0;i<askArray.size();i++){
					
					JSONArray subbids = (JSONArray)bidsArray.getJSONArray(i);
					String buycount = subbids.getString(1);
					String buyprice = subbids.getString(0);
					JSONArray subask = (JSONArray)askArray.getJSONArray(askArray.size()-1-i);
					String sellcount = subask.getString(1);
					String sellprice = subask.getString(0);					
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("buycount", buycount);
					map.put("buyprice", buyprice);
					map.put("sellprice", sellprice);
					map.put("sellcount", sellcount);
					depthDataList.add(map);				
				}
				
				String return_trade_data = Util.getHtml(ConfigDef.CHINA_BITER_TRADE, "utf-8");
				JSONArray tradeDataArray = JSONArray.fromObject(return_trade_data);
				for(int j=tradeDataArray.size()-1;j>=0;j--){
					JSONObject object = tradeDataArray.getJSONObject(j);
					Map<String, Object> map = new HashMap<String, Object>();
					long datatime = object.getLong("date")*1000L;
					Log.v(TAG, String.valueOf(datatime));
					Date date = new Date(datatime);
					map.put("date", Formater.formatDateTime(date));
					map.put("price", object.getString("price"));
					map.put("amount", object.getString("amount"));
					map.put("type", object.getString("type"));
					map.put("tid", object.getString("tid"));
					tradeDataList.add(map);
				}
				
				
				String return_ticker_data = Util.getHtml(ConfigDef.CHINA_BITER_TICKER, "utf-8");
				
				Message msg = new Message();
				msg.what = 1;
				msg.obj = return_ticker_data;
				myHandler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent intent = new Intent(QuotationActivity.this,SettingActivity.class);
			this.startActivity(intent);
			break;
		case R.id.action_quo_refresh:
			(new Thread(new getDepthData())).start();
			break;
		case R.id.action_pays:
            Util.show_pay(context);
			break;
		default:
			break;
		}

		return super.onMenuItemSelected(featureId, item);
	}
	
}
